import axios from "axios";

var instance = axios.create({
  baseURL: "http://127.0.0.1:8000",
  timeout: 8000,
});

instance.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem("token");
    config.headers.authorization = `bearer ${token}`;

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  function (res) {
    const { authorization } = res.headers;
    authorization && localStorage.setItem("token", authorization);
    return res;
  },
  function (error) {
    if (error.response?.status === 401) {
      localStorage.removeItem("token");
      location.href = "/login";
    }

    return Promise.reject(error);
  }
);

export default instance;
